//职员管理

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Button, Table, Modal, Row, Col, Upload, Icon, DatePicker, Select} from 'antd';
import {project, activity} from '../value';
import '../css/other.css';
import moment from 'moment';
import {config} from "../config";
import {ChooseGoods} from '../components/operateManage';


const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const TextArea = Input.TextArea;

class ActivityAdd extends Component {
    constructor(props) {
        super(props);
        this.state = {
            goodList: [],
            allNumber: 0,
            currentType: '新建',
            manData: [
                {
                    activity_condition: 10,
                    activity_discount: 1
                }
            ]
        }
    }

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    columns = [
        {
            title: '序号',
            dataIndex: 'order_number'
        },
        {
            title: '图片',
            dataIndex: 'file_path',
            render: file_path => {
                return (
                    <img className={"projectImg"} src={config.imgServerUrl + file_path}/>
                )
            }
        },
        {
            title: '商品名',
            dataIndex: 'goods_name'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <Button style={{marginLeft: '10px'}} type="danger"
                            onClick={() => this.handleDeleteGood(data.order_number)}>删除</Button>
                )
            }
        },
    ];

    render() {
        const {getFieldDecorator} = this.props.form;
        const {allNumber, currentType,operateType,activity_id} = this.state;
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    {currentType}活动
                </div>
                <Row style={{marginTop: 20}}>
                    <FormItem label={"活动名称"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('activity_name', {
                            rules: [{required: true, message: '请输入活动名称'}],
                        })(
                            <Input
                                placeholder="请输入活动名称" style={{width: '300px'}}/>
                        )}
                    </FormItem>
                    <FormItem label={"活动说明"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('activity_explain', {
                            rules: [{required: true, message: '请输入活动说明'}],
                        })(
                            <TextArea
                                placeholder="请输入活动说明" style={{width: '300px'}}/>
                        )}
                    </FormItem>
                    <FormItem label={"活动类型"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('activity_type', {
                            rules: [{required: true, message: '请选择活动类型'}],
                        })(
                            <Select style={{width: 300}} placeholder={'请选择活动类型'}>
                                <Option value="1">满减</Option>
                                <Option value="2">折扣</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem label={"满减金额"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('man')(
                            <div>
                                {
                                    this.state.manData.map((item, index) => {
                                        return (
                                            <div className={"man-item"} key={index}>
                                                <Input
                                                    placeholder="" style={{width: '100px'}}
                                                    value={item.activity_condition}
                                                    onChange={(e) => this.handleValueOnChange(e, index, 1)}
                                                    type={'number'}
                                                />
                                                <div style={{width: 30, textAlign: 'center'}}>减</div>
                                                <Input
                                                    placeholder="" style={{width: '100px'}}
                                                    value={item.activity_discount}
                                                    onChange={(e) => this.handleValueOnChange(e, index, 2)}
                                                    type={'number'}
                                                />
                                                {
                                                    (index + 1) === this.state.manData.length ?
                                                        <Button type={'primary'}
                                                                onClick={() => this.handleAddMan(index)}>增加</Button>
                                                        :
                                                        <Button type={'danger'}
                                                                onClick={() => this.handleDeleteMan(index)}>删除</Button>
                                                }
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        )}
                    </FormItem>
                    <FormItem label={"活动开始时间"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('activity_startTime', {
                            rules: [{required: true, message: '请设置活动开始时间'}],
                        })(
                            <DatePicker style={{width: 300}}/>
                        )}
                    </FormItem>
                    <FormItem label={"活动结束时间"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('activity_endTime', {
                            rules: [{required: true, message: '请设置活动结束时间'}],
                        })(
                            <DatePicker style={{width: 300}}/>
                        )}
                    </FormItem>
                    <FormItem label={"商品选择"} style={{display: 'flex'}} {...this.formItemLayout}>
                        {getFieldDecorator('goods')(
                            <div style={{display: 'flex'}}>
                                <ChooseGoods data={this.state.goodList} operateType={operateType}
                                             handleChoose={(data) => this.handleChoose(data)}
                                             activity_id={activity_id}
                                />
                                <div style={{width: 100, marginLeft: 5}}>已选{allNumber}</div>
                            </div>
                        )}
                    </FormItem>
                    <Row>
                        <Col span={10} offset={6}>
                            <Table
                                columns={this.columns}
                                rowKey={(record, index) => index}
                                dataSource={this.state.goodList}
                                loading={this.state.loading}
                                pagination={false}
                                onChange={this.handleTableChange}
                            />
                        </Col>
                    </Row>
                    <Row style={{textAlign: 'center', marginTop: 20}}>
                        <Col span={8} offset={6}>
                            <Button type={'primary'} onClick={(e) => this.handleSubmit(e)}>确认并提交</Button>
                        </Col>
                    </Row>
                </Row>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        const activity_id = this.props.match.params.id;
        console.log(activity_id);
        if (!activity_id || activity_id === ':id') {
            this.setState({currentType: '新建', operateType: 1, activity_id: ''});
        } else {
            this.setState({currentType: '编辑', operateType: 2, activity_id: activity_id});
            this.searchActivityOne({activity_id});
        }
    }


    /**
     * 查找单个满减活动详情
     * @param param
     */
    searchActivityOne(param) {
        let _this = this;
        app.post(activity.SEARCH_ACTIVITY_ONE, param).then(result => {
            if (result.code === 1) {
                const {activity_endTime,activity_explain,activity_name,activity_startTime,activity_type,conditionList,goodsList} = result.data;
                for (let i = 0; i < goodsList.length; i++) {
                    goodsList[i].order_number = i + 1;
                }
                _this.setState({goodList:goodsList,allNumber:goodsList.length,manData:conditionList});
                let formData=[];
                formData['activity_name']={value:activity_name};
                formData['activity_explain']={value:activity_explain};
                formData['activity_type']={value:activity_type};
                formData['activity_startTime'] = {value: moment(activity_startTime, 'YYYY-MM-DD')};
                formData['activity_endTime'] = {value: moment(activity_endTime, 'YYYY-MM-DD')};
                _this.props.form.setFields(formData);
            } else {
                app.alert(result.msg, 'info', 1);
            }
        });
    }

    /**
     * 处理选择商品事件
     * @param data
     */
    handleChoose(data) {
        for (let i = 0; i < data.length; i++) {
            data[i].order_number = i + 1;
        }
        this.setState({goodList: data, allNumber: data.length});
    }

    /**
     * 删除商品
     * @param index
     */
    handleDeleteGood(index) {
        let goodList = this.state.goodList;
        goodList.splice(index - 1, 1);
        for (let i = 0; i < goodList.length; i++) {
            goodList[i].order_number = i + 1;
        }
        this.setState({goodList, allNumber: goodList.length});
    }

    /**
     * 处理提交事件
     * @param e
     */
    handleSubmit(e) {
        e.preventDefault();
        let {manData, goodList,operateType,activity_id} = this.state;
        if (manData.length <= 0) {
            app.alert('请设置满减金额', 'info', 1);
            return;
        }
        const {activity_condition, activity_discount} = manData[manData.length - 1];
        if (!activity_condition || activity_condition <= 0 || !activity_discount || activity_discount <= 0) {
            app.alert('请先设置完整满减金额', 'info', 1);
            return;
        }
        if (goodList.length <= 0) {
            app.alert('请选择商品', 'info', 1);
            return;
        }
        let goodLists = [];
        for (let i = 0; i < goodList.length; i++) {
            let item = {
                goods_id: goodList[i].goods_id
            };
            goodLists.push(item);
        }
        this.props.form.validateFields((error, values) => {
            if (!error) {
                let startTime = moment(values.activity_startTime._d).format('YYYY-MM-DD HH:mm:ss').valueOf();
                let endTime = moment(values.activity_endTime._d).format('YYYY-MM-DD HH:mm:ss').valueOf();
                if (endTime <= startTime) {
                    app.alert('结束时间必须大于开始时间');
                    return;
                }
                values.activity_startTime = moment(values.activity_startTime._d).format('YYYY-MM-DD HH:mm:ss');
                values.activity_endTime = moment(values.activity_endTime._d).format('YYYY-MM-DD HH:mm:ss');
                values.conditionList = manData;
                values.goodsList = goodLists;
                console.log(values);
                if(operateType===1){
                    app.post(activity.ADD_ACTIVITY, values).then((res) => {
                        if (res.code === 1) {
                            app.alert('添加成功', 'success', 1);
                        } else {
                            app.alert(res.msg, 'info', 1);
                        }
                    })
                }else if(operateType===2){
                    values.activity_id=activity_id;
                    app.post(activity.UPDATE_ACTIVITY, values).then((res) => {
                        if (res.code === 1) {
                            app.alert('编辑成功', 'success', 1);
                        } else {
                            app.alert(res.msg, 'info', 1);
                        }
                    })
                }
            }
        })
    }

    /**
     * 处理满减金额输入框变化事件
     * @param e
     * @param index
     * @param type
     */
    handleValueOnChange(e, index, type) {
        let manData = this.state.manData;
        if (type === 1) {
            manData[index].activity_condition = e.target.value;
        } else if (type === 2) {
            manData[index].activity_discount = e.target.value;
        }
        this.setState({manData});
    }

    /**
     * 增加满减金额
     * @param index
     */
    handleAddMan(index) {
        let manData = this.state.manData;
        let {activity_condition, activity_discount} = manData[index];
        if (activity_condition && activity_condition > 0 && activity_discount && activity_discount > 0) {
            manData.push({activity_condition: 0, activity_discount: 0});
            this.setState({manData});
        } else {
            app.alert('请先设置完整满减金额', 'error', 1);
        }
    }

    /**
     * 删除满减金额
     * @param index
     */
    handleDeleteMan(index) {
        let manData = this.state.manData;
        manData.splice(index, 1);
        this.setState({manData});
    }

}

const ActivityAdds = Form.create()(ActivityAdd);

export default ActivityAdds


